import React, { useEffect} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import routes, {Route} from "../routes";
import {useDispatch, useSelector} from "react-redux";
import {getCurrentUser} from "../../stores/userReducer";
// @ts-ignore
const getCurrentRouterMap=(route: Route[],path: string)=>{
    for(let r of route){
        if(r.path==path){
            return r;
        }
        if(r.children){
            // @ts-ignore
            let res=getCurrentRouterMap(r.children,path);
            if(res){
                return res;
            }
        }

    }
};
type ChildrenProps={
    children:React.ReactNode;
}
const RouterBeforeEach:React.FC<ChildrenProps>=(props: ChildrenProps)=>{
    const location=useLocation();
    const navigator=useNavigate();
    const dispatch=useDispatch()
    //@ts-ignore
    const userInfo=useSelector((state)=>{return  state.user.userInfo})
    useEffect(()=>{
        // let router=getCurrentRouterMap(routes,location.pathname);
        // @ts-ignore
        dispatch(getCurrentUser())
        if(!userInfo?.userRole){
            navigator('/user/login');
        }
    },[location]);
    return (<>{props.children}</>);
}
export default RouterBeforeEach;
